package logic

import (
	"context"
	"encoding/json"
	"furni-manager/model/cache"
	"furni-manager/model/mysql"
	"time"

	"furni-manager/furnirpc/furnirpc"
	"furni-manager/furnirpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type FurniListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewFurniListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *FurniListLogic {
	return &FurniListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *FurniListLogic) FurniList(in *furnirpc.FurniListRequest) (*furnirpc.FurniListResponse, error) {
	// todo: add your logic here and delete this line

	var furnis []mysql.Furni

	result, _ := cache.Rdb.Get(l.ctx, "redis_list_").Result()

	if result == "" {
		mysql.DB.Debug().Find(&furnis)
		jsonData, _ := json.Marshal(furnis)
		cache.Rdb.Set(l.ctx, "redis_list_", jsonData, time.Hour*1)
	} else {
		json.Unmarshal([]byte(result), &furnis)
	}

	var furniList []*furnirpc.FurniList

	for _, furni := range furnis {
		list := furnirpc.FurniList{
			FurniId: int64(furni.ID),
			Name:    furni.Name,
			Price:   float32(furni.Price),
			Stock:   int64(furni.Stock),
		}
		furniList = append(furniList, &list)
	}

	return &furnirpc.FurniListResponse{
		List: furniList,
	}, nil
}
